/** 生成N位随机数
 * @param len
 * @returns
 */
export const randomstring = (len = 32): string => {
  len = len || 32;
  const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
  const maxPos = chars.length;
  let str = "";
  for (let i = 0; i < len; i++) {
    str += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return str;
};

/** 获取指定字符串前的内容
 * @param {String} str 字符串
 * @param {identifier} str 指定字符串
 * @returns {string}
 */
export const getPrefixStr = (str: string, identifier = "."): string => {
  const pos = str.indexOf(identifier);
  let suffix = "";
  if (pos !== -1) {
    suffix = str.substring(0, pos);
  }
  try {
    return decodeURI(suffix);
  } catch (err) {
    return suffix;
  }
};
/** 从最右端获取指定字符串后的内容
 * @param {String} str 字符串
 * @param {identifier} str 指定字符串
 * @returns {string}
 */
export const getSuffixStr = (str: string, identifier = "."): string => {
  const pos = str.lastIndexOf(identifier);
  let suffix = "";
  if (pos !== -1) {
    suffix = str.substring(pos + 1);
  }
  try {
    return decodeURI(suffix);
  } catch (err) {
    return suffix;
  }
};

/**
 * 递归展开多维数组为一维数组
 * @param arr 任意多维数组
 * @returns 一维数组
 */
export const spreadOutList = (arr: any[]): any[] => {
  return [].concat(
    ...arr.map((item) => (Array.isArray(item) ? spreadOutList(item) : item))
  );
};

/**
 * 根据指定 key 对对象数组去重
 * @param list 对象数组
 * @param key 需要去重的字段名
 * @returns 去重后的新数组
 */
export const duplicateRemovalList = (list: any[], key: string) => {
  return [...new Map(list.map(item => [item[key], item])).values()];
};